<!--
 * @Author: fisher
 * @Date: 2024-02-12 22:06:04
 * @LastEditors: fisher luthor-li@qq.com
 * @LastEditTime: 2024-03-11 21:13:38
 * @FilePath: \allfront\src\App.vue
 * @Description: 
-->
<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue';
import { initWatchMap, handleMsg } from '@/utils/appMsg';
// 初始化ws需要监听的数据store列表
initWatchMap();
const socket = ref(null);
onMounted(() => {
  // const host = import.meta.env.VITE_APP_HOST;
  // const port = import.meta.env.VITE_APP_PORT;
  const host = window.location.host;
  socket.value = new WebSocket(`ws://${host}/appMsg`);

  socket.value.addEventListener('open', function (event) {
    console.log('Connected to WS Server', event);
    // 如果需要，可以发送初始状态到服务器
    socket.value.send('Client connected');
  });

  socket.value.addEventListener('message', function (event) {
    console.log('Message from server ', event);
    handleMsg(event.data);
  });

  // 处理 WebSocket 错误
  socket.value.addEventListener('error', function (event) {
    console.log('WebSocket error: ', event);
  });
});
onBeforeUnmount(() => {
  // 组件卸载之前，关闭 WebSocket 连接
  if (socket.value) {
    socket.value.close();
  }
});
</script>

<template>
  <router-view></router-view>
</template>

<style scoped></style>
